package com.course.servlet;

import com.course.entity.Student;
import com.course.service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private final StudentService studentService;

    public LoginServlet() {
        this.studentService = new StudentService();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        Student student = studentService.login(username, password);

        if (student != null) {
            // 登录成功，将学生信息存入session
            HttpSession session = request.getSession();
            session.setAttribute("student", student);
            session.setAttribute("username", student.getUsername());
            // 重定向到首页
            response.sendRedirect("index.jsp");
        } else {
            // 登录失败，返回错误信息
            request.setAttribute("error", "用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
} 